#pragma once
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string.h>
#include <string>
#include <unistd.h>

using namespace std;

class Sock
{
public:
    static int Socket()
    {
        int sock = socket(AF_INET, SOCK_STREAM, 0);
        if(sock < 0)
        {
            cerr << "sock error " << endl;
            exit(2);
        }
        return sock;
    }

    static void Bind(const int sock, const uint16_t port)
    {
        struct sockaddr_in local;
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;
        if(bind(sock, (struct sockaddr*)&local, sizeof(local)))
        {
            cerr << "bind error " << endl;
            exit(3);
        }
    }

    static void Listen(const int& listen_sock)
    {
        if(listen(listen_sock, 5) < 0)
        {
            cerr << "listen error " << endl;
            exit(4);
        }
    }

    static int Accept(const int& listen_sock)
    {
        struct sockaddr_in local;
        socklen_t len = sizeof(local);
        int new_sock = accept(listen_sock, (struct sockaddr*)&local, &len);
        if(new_sock < 0)
        {
            cerr << "accept error " << endl;
            exit(5);
        }
        cout << "get a link " << endl;

        return new_sock;
    }

    static void Connect(int sock, const uint16_t& port, const std::string& ip)
    {
        struct sockaddr_in server;
        server.sin_family = AF_INET;
        server.sin_port = htons(port);
        server.sin_addr.s_addr = inet_addr(ip.c_str());
        if(connect(sock, (struct sockaddr*)&server, sizeof(server)) == 0)
        {
            cout << "connect success " << endl;
        }
        else
        {
            cerr << "connect error " << endl;
            exit(6); 
        }
    }
};